package spiders

import (
	"github.com/PuerkitoBio/goquery"
	"github.com/gookit/color"
	"go-car/model"
	"regexp"
	"strconv"
	"strings"
)

var compileNumber = regexp.MustCompile("[0-9]")

func GetCityName(doc *goquery.Document) string {
	return doc.Find(".citycont .fn-left").Text()
}

func GetCurrentPage(doc *goquery.Document) (page int) {
	pageS := doc.Find(".page .current").Text()
	if pageS != "" {
		var err error
		page, err = strconv.Atoi(pageS)
		if err != nil {
			color.Error.Printf("GetCurrentPage err: %v\n", err)
		}
	}

	return page
}

func GetNextPageUrl(doc *goquery.Document) (val string, exists bool) {
	return doc.Find(".page .page-item-next").Attr("href")
}

func GetCars(doc *goquery.Document) (cars []model.QcCar) {
	cityName := GetCityName(doc)
	doc.Find(".piclist ul li:not(.line)").Each(func(i int, s *goquery.Selection) {
		title := s.Find(".title a").Text()
		price := s.Find(".detail .detail-r").Find(".colf8").Text()
		kilometer := s.Find(".detail .detail-l").Find("p").Eq(0).Text()
		year := s.Find(".detail .detail-l").Find("p").Eq(1).Text()

		kilometer = strings.Join(compileNumber.FindAllString(kilometer,-1),"")
		year = strings.Join(compileNumber.FindAllString(strings.TrimSpace(year),-1),"")
		priceS, _ := strconv.ParseFloat(price, 64)
		kilometerS, _ := strconv.ParseFloat(kilometer, 64)
		yearS,_ := strconv.Atoi(year)

		cars = append(cars, model.QcCar{
			CityName:  cityName,
			Title:     title,
			Price:     priceS,
			Kilometer: kilometerS,
			Year:      yearS,
		})

	})

	return cars
}
